package com.yanqu.road.server.cmd.mall;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.eItemId;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.log.LogGoldTokenBuy;
import com.yanqu.road.entity.recharge.GoldTokenRechargeResult;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.config.ServerConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.mall.MallProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityMallModule;
import com.yanqu.road.server.gameplayer.module.activity.pixiu.PiXiuModule;
import com.yanqu.road.server.gameplayer.module.mall.MallModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.gameplayer.module.player.RechargeModule;
import com.yanqu.road.server.logic.recharge.limit.BaseRMBMallLimit;
import com.yanqu.road.server.logic.recharge.limit.MallLimitFactory;
import com.yanqu.road.server.manger.DataAnalyticsMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.VipMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.config.MallMgr;
import com.yanqu.road.server.manger.config.MallRechargeConfigMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.thirdparty.ThirdPartyMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;

@Cmd(code = Protocol.S_MALL_GOLD_TOKEN_BUY_GOODS, desc = "代币购买")
public class GoldTokenBuyGoodsCmd extends AbstractCommand {

	private int mallId;
	private int count;
	private int activityId;
	private String reward;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		MallProto.GoldTokenBuyGoodsReqMsg reqMsg = MallProto.GoldTokenBuyGoodsReqMsg.parseFrom(packet.getBytes());
		mallId = reqMsg.getMallId();
		count = reqMsg.getCount();
		activityId = reqMsg.getActivityId();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		//订阅商品不能通宝购买
		if(GameConfig.SUBSCRIBE_WEEK_CARD_MALL_ID == mallId){
			ret = GameErrorCode.E_MALL_LIMIT_BUY;
			return;
		}
		//入口开关
		if(ServerConfig.GOLD_TOKEN_BUY_SWITCH == 0){
			ret = GameErrorCode.E_SYSTEM_NO_OPEN;
			return;
		}

		//检查购买数量，目前只能一个个购买，数量目前没用，购买逻辑只写一个来的，后面如果要变多个，逻辑需要重新处理
		if (count < 1 || count > GameConfig.GOLD_TOKEN_BUY_MAX_COUNT) {
			ret = GameErrorCode.E_MALL_GOLD_TOKEN_BUY_COUNT_ERROR;
			return;
		}


		MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
		if (null == mallInfo) {
			ret = GameErrorCode.E_MALL_NO_EXIST;
			return;
		}

		//检查付费项编号
		if(mallInfo.getRechargeId() < 0){
			ret = GameErrorCode.E_MALL_CONFIG_ERROR;
			return;
		}

		ActivityInfo activityInfo = null;
		if(activityId > 0) {//有活动编号，判断活动信息
			activityInfo = ActivityMgr.getOpenActivityInfo(activityId);
			if (null == activityInfo) {//不在活动时间
				ret = GameErrorCode.E_ACTIVITY_NO_IN_TIME_CANNOT_BUY;
				return;
			}
		}

		//vip等级限购
		int vipLevel = VipMgr.getVipLv(player.getModule(PlayerModule.class).getUserInfo().getVipExp());
		if (vipLevel < mallInfo.getVipLimit()) {
			ret = GameErrorCode.E_MALL_LIMIT_BUY_VIP;
			return;
		}

		//系统解锁限制
		if (mallInfo.getSystemLimit().size() > 0) {
			for (Integer systemId : mallInfo.getSystemLimit()) {
				if (!SystemOpenMgr.systemOpen(player, systemId)) {
					ret = GameErrorCode.E_SYSTEM_NO_OPEN;
					return;
				}
			}
		}

		//检查价格的配置
		long vipExp = MallRechargeConfigMgr.getParamValue(mallInfo);
//		int vipExp = StringUtils.string2intSafe(mallInfo.getParam(), 0);
		if(vipExp <= 0){
			ret = GameErrorCode.E_MALL_CONFIG_ERROR;
			return;
		}

		BaseRMBMallLimit baseRMBMallLimit = MallLimitFactory.getMallLimit(player.getUserId(), mallInfo, activityInfo);
		if(null == baseRMBMallLimit){
			ret = GameErrorCode.E_MALL_LIMIT_BUY;
			return;
		}
		ret = baseRMBMallLimit.checkMallLimit().getRet();
		if(0 != ret){
			return;
		}

		//消耗
		Property consume = MallMgr.getGoldTokenConsume(count, player.getModule(MallModule.class).getMallBuyCount(mallId), mallInfo);
		if (!player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.Mall, eLogMoneyType.GoldTokenBuy, mallId + ":" + count)) {
			ret = GameErrorCode.E_BAG_GOLD_TOKEN_NO_ENOUGH;
			return;
		}
		long oldVipExp = player.getUserInfo().getVipExp();
		String actType = ActivityMgr.getActType(mallInfo, activityInfo);

		//记录通宝购买数量,临时
		BigInteger consumeNum = consume.getCountByGoodsId(eItemId.GOLD_TOKEN.getValue());

		GoldTokenRechargeResult goldTokenRechargeResult = player.getModule(RechargeModule.class).goldTokenRecharge(mallInfo, activityInfo);
		ret = goldTokenRechargeResult.getRet();
		reward = goldTokenRechargeResult.getReward();
		if(0 == ret) {
			long serverId = ConfigHelper.getLong("serverId");
			long moneyPrice = MallRechargeConfigMgr.getPrice(mallInfo);
//			long moneyPrice = StringUtils.string2longSafe(mallInfo.getPrice(), 0);
			moneyPrice = moneyPrice * count;
			AutoLogMgr.add(new LogGoldTokenBuy(player.getUserId(), mallInfo.getMallId(), count, PropertyHelper.parsePropertyToString(consume),
					oldVipExp, player.getUserInfo().getVipExp(), activityId, actType, player.getPhonePlatform(), reward, moneyPrice + "",
					mallInfo.getMallMarkId() == 0 ? mallInfo.getMallId() : mallInfo.getMallMarkId(), DataAnalyticsMgr.getChannelPayType(serverId)));
			player.getModule(PiXiuModule.class).addUseToken(consumeNum.longValue());
			player.getModule(ActivityMallModule.class).extendOperation(mallInfo);

			int chancePrice = consume.getCountByGoodsId(eItemId.GOLD_TOKEN.getValue()).intValue();
			int channelId = ServerListMgr.getChannelId(GameServer.getInstance().getServerId());
			TokenBuyReportTask task = new TokenBuyReportTask(player.getUserInfo().getPlatformUserId(),
					player.getUserInfo().getOriginalServerId(),
					String.valueOf(channelId),
					player.getAppId(),
					DateHelper.getCurrentTime(),
					chancePrice,
					mallInfo.getMallMarkId() == 0 ? mallInfo.getMallId() : mallInfo.getMallMarkId(),
					mallInfo.getMallName(),
					""
			);
			ThirdPartyMgr.addTask(task);
		} else {
			log.error("玩家{}，通宝购买 {} 未成功，异常扣除通宝数量 {}", player.getUserId(), mallInfo.getMallId(), consumeNum.longValue());
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		MallProto.GoldTokenBuyGoodsRespMsg.Builder respMsg = MallProto.GoldTokenBuyGoodsRespMsg.newBuilder();
		respMsg.setRet(ret);
		respMsg.setMallId(mallId);
		if(!StringUtils.isNullOrEmpty(reward)){
			respMsg.setReward(reward);
		}
		player.sendPacket(Protocol.U_MALL_GOLD_TOKEN_BUY_GOODS, respMsg);
	}
}
